<template>
  <div class="purchase-statistics-container">
    <!-- 图表区域 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <div class="chart-title">月度采购趋势</div>
            <div ref="monthlyTrendChart" class="chart"></div>
          </el-card>
        </el-col>
        <!-- <el-col :span="12">
          <el-card>
            <div class="chart-title">供应商采购占比</div>
            <div ref="vendorPieChart" class="chart"></div>
          </el-card>
        </el-col> -->
      </el-row>
    </div>

    <!-- 统计卡片区域（修复布局后） -->
    <div class="statistics-overview">
      <el-row :gutter="20" justify="space-between">
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">订单总数</div>
              <div class="stat-value">{{ count }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">采购总额</div>
              <div class="stat-value">¥{{ caigouzonjine }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">平均单价</div>
              <div class="stat-value">¥{{ danjia }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">供应商数</div>
              <div class="stat-value">{{ vendornumer }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 订单明细表格 -->
    <div class="detail-table">
      <el-card>
        <div class="table-header">
          <div class="table-title">采购订单明细</div>
          <div class="table-actions">
            <el-button type="primary" @click="exportExcel">导出Excel</el-button>
          </div>
        </div>
        <el-table
          :data="tabledatapo"
          border
          style="width: 100%"
          v-loading="loading"
          ref="customerTable"
        >
          <el-table-column prop="po_Code" label="订单编号" width="190" />
          <el-table-column prop="po_date" label="订单日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.po_Starttime) }}
            </template>
          </el-table-column>
          <el-table-column prop="po_Vendor_Name" label="供应商" width="180" />
          <el-table-column prop="je" label="订单金额" width="120">
            <template #default="{ row }">
              <span>¥{{ zjevalue(row) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="product_count" label="产品数量" width="100">
            <template #default="{ row }">
              <span>¥{{ shulvalue(row) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="po_State" label="订单状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.po_State)">
                {{ getStatusText(row.po_State) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="pb_code" label="入库单号" width="160">
            <template #default="scoped">
              <span>{{ pb_codevalue(scoped.row.po_Code) }}</span>
            </template>
            </el-table-column>
          <el-table-column prop="pb_Inboundtime" label="入库日期" width="120">
            <template #default="scoped">
              <span>{{ formatDate(pb_timevalue(scoped.row.po_Code)) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="text" @click="viewDetail(row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-center">
        <el-pagination
          small
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted,toRaw } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router';
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { useStore } from 'vuex'

export default {
  setup() {
    const customerTable = ref(null);

    const store = useStore();
    const datamax = store.state.PO_UpdeteArray

    const Router = useRouter();
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const tabledatapo = ref([])//用于展示表格数据

    const count = ref(0) // 订单总数
    const tableData = ref([]) // 订单明细数据(用于计算采购金额和数量)
    const danjia = ref(0) // 平均单价
    const caigouzonjine = ref(0) // 采购总金额（元）
    const vendornumer = ref(0) // 供应商数量

    const monthlyTrendChart = ref(null) // 月度趋势图 DOM 引用
    const vendorPieChart = ref(null) // 供应商占比图 DOM 引用（示例未实现）

    const pbdata = ref([]);//采购入库信息

    // 生命周期钩子：组件挂载后初始化
    onMounted(() => {
            getPB();//加载采购订单入库单号

      Counts() // 获取订单总数
      initData() // 获取订单明细数据
      vendorCount() // 获取供应商数量
      initMonthlyTrendChart() // 初始化月度趋势图（会在数据加载后自动更新）
      infoPO()
      infoPOCount()
    })

    // ------------------------------ 数据获取函数 ------------------------------
    // 查询订单总数
    function Counts() {
      axios.get("http://localhost:5181/api/Po/GetPoCount", {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((res) => {
        count.value = res.data
      }).catch((err) => {
        ElMessage.error('订单总数加载失败')
      })
    }
    function getPB(){
      axios.get('http://localhost:5181/api/Pb/GetPbFyWhere',{
        params: {
            currentPage: 1,
            pageSize: 999 // 获取所有数据用于统计
          },
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
      }).then((result) => {
        pbdata.value = result.data;
        // console.log(pbdata.value)
      }).catch((err) => {
        ElMessage.error('采购入库单号加载失败')
      });
    }
    function pb_codevalue(row){
      if (!row) return "无";
        // console.log(row)
        const parentUser = pbdata.value.find((d) => d.po_code == row)
        return parentUser ? parentUser.pb_code : "无"
    }
    function pb_timevalue(row){
      if (!row) return "无";
        // console.log(row)
        const parentUser = pbdata.value.find((d) => d.po_code == row)
        return parentUser ? parentUser.pb_Inboundtime : "无"
    }

    // 获取订单明细数据（含详情）
    async function initData() {
      try {
        const res = await axios.get('http://localhost:5181/api/Po/GetPoFYWhereAudit', {
          params: {
            currentPage: 1,
            pageSize: 999999 // 获取所有数据用于统计
          },
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        tableData.value = res.data
        // console.log(tableData.value)
        
        // 计算总金额和总数量（用于统计指标）
        caigouzonjine.value = res.data.reduce((sum, order) => {
          if (!order.details || !order.details.length) return sum
          return sum + order.details.reduce((detailSum, detail) => {
            return detailSum + (detail.po_number || 0) * (detail.details_monovalent || 0)
          }, 0)
        }, 0).toFixed(2)

        const totalQuantity = res.data.reduce((sum, order) => {
          if (!order.details || !order.details.length) return sum
          return sum + order.details.reduce((detailSum, detail) => {
            return detailSum + (detail.po_number || 0)
          }, 0)
        }, 0)

        danjia.value = totalQuantity > 0 
          ? (caigouzonjine.value / totalQuantity).toFixed(2) 
          : '0.00'

        initMonthlyTrendChart() // 数据加载完成后重新渲染趋势图
      } catch (err) {
        ElMessage.error('订单明细加载失败')
      }
    }

    function infoPO(){
      axios.get('http://localhost:5181/api/Po/GetPoFYWhereAudit', {
        params: {
          currentPage: currentPage.value,
          pageSize: pageSize.value, // 获取所有数据用于统计
        },
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        // console.log(result.data)
        tabledatapo.value = result.data
        console.log(tabledatapo.value)
      })
    }
    function infoPOCount(){
      axios.get('http://localhost:5181/api/Po/GetPoCountAudit', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      })
    }
    function handleSizeChange(val) {
      pageSize.value = val
      infoPO()
    }
    
    function handleCurrentChange(val) {
      currentPage.value = val
      infoPO()
    }


    // 获取供应商数量
    function vendorCount() {
      axios.get('http://localhost:5181/api/Values/Pinv_VendorCount', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((res) => {
        vendornumer.value = res.data
      }).catch((err) => {
        ElMessage.error('供应商数量加载失败')
      })
    }

    // ------------------------------ 图表初始化函数 ------------------------------
    // 初始化月度采购趋势图
    function initMonthlyTrendChart() {
      if (!monthlyTrendChart.value) return

      const chart = echarts.init(monthlyTrendChart.value)
      const monthlyData = calculateMonthlyPurchase() // 获取月度采购数据（元）

      // 配置图表选项
      const option = {
        title: {
          text: '月度采购金额趋势',
          left: 'center',
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>采购金额: ¥{c}'
        },
        xAxis: {
          type: 'category',
          data: monthlyData.map(item => item.month),
          axisLabel: {
            rotate: 45, // 旋转避免重叠
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          name: '金额（元）',
          axisLabel: {
            formatter: '¥{value}', // 金额格式化
            fontSize: 12
          }
        },
        series: [
          {
            name: '采购金额',
            type: 'line',
            data: monthlyData.map(item => item.amount),
            smooth: true,
            symbolSize: 8,
            itemStyle: {
              color: '#409EFF' // Element Plus 主题蓝
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            }
          }
        ],
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          top: '15%'
        }
      }

      chart.setOption(option)
      window.addEventListener('resize', () => chart.resize())
    }
    // ------------------------------ 计算单个订单采购金额 ------------------------------
    function zjevalue(row){
      if (!row.details || row.details.length === 0) return 0;
    
      // 使用reduce计算所有明细项的总和
      const total = row.details.reduce((sum, detail) => {
        return sum + (detail.po_number * detail.details_monovalent);
      }, 0);
      
      return total.toFixed(2); // 保留两位小数
    }
    // ------------------------------ 计算单个订单采购数量 ------------------------------
    function shulvalue(row){
      if (!row.details || row.details.length === 0) return 0;
    
      // 使用reduce计算所有明细项的总和
      const total = row.details.reduce((sum, detail) => {
        return sum + detail.po_number;
      }, 0);
      
      return total.toFixed(2); // 保留两位小数
    }

    // 计算月度采购数据（核心函数，返回元单位）
    function calculateMonthlyPurchase() {
      const monthlyMap = {} // 存储 { 月份: 总金额（元） }

      tableData.value.forEach(order => {
        if (!order.details || !order.details.length) return // 跳过无详情的订单

        // 解析订单日期（po_Starttime）获取年月（格式：YYYY-MM）
        const orderDate = dayjs(order.po_Starttime)
        const monthKey = orderDate.format('YYYY-MM-DD')

        // 计算该订单的总金额（详情中数量*单价之和）
        const orderTotal = order.details.reduce((sum, detail) => {
          return sum + (detail.po_number || 0) * (detail.details_monovalent || 0)
        }, 0)

        // 累加到对应月份的金额
        monthlyMap[monthKey] = (monthlyMap[monthKey] || 0) + orderTotal
      })

      // 转换为数组并按月份排序
      return Object.entries(monthlyMap)
        .map(([month, amount]) => ({ month, amount }))
        .sort((a, b) => a.month.localeCompare(b.month))
    }

    // ------------------------------ 辅助函数 ------------------------------
    // 格式化日期（使用 po_Starttime 字段）
    function formatDate(dateStr) {
      return dayjs(dateStr).format('YYYY-MM-DD')
    }

    // 获取订单状态文本
    function getStatusText(state) {
      const statusMap = {
        0: '未入库',
        2: '部分入库',
        3: '已完成',
        8: '未入库',
        7: '部分退货',
        6: '超额退货',
        9: '全部退货'
      }
      return statusMap[state] || '异常状态'
    }

    // 获取订单状态标签类型
    function getStatusTagType(state) {
      const typeMap = {
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      }
      return typeMap[state] || 'info'
    }

    function getTableHeaders() {
      if (customerTable.value) {
        const filteredColumns = customerTable.value.columns.filter(column => {
          return column.label !== '操作'
        })
        const headers = filteredColumns.map(column => column.label)
        return headers
      }
      return []
    }
    // 导出Excel（示例未实现）
   async function exportExcel() {
  try {
    // 获取所有订单数据（用于导出）
    const response = await axios.get('http://localhost:5181/api/Po/GetPoFYWhereAudit', {
      params: {
        currentPage: 1,
        pageSize: 999999 // 获取所有数据用于导出
      },
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    const allOrders = response.data

    // 定义表头
    const headers = [
      '订单编号',
      '订单日期',
      '供应商',
      '订单金额',
      '产品数量',
      '订单状态',
      '入库单号',
      '入库日期',
      '联系人',
      '联系电话',
      '创建人',
      '备注',
      '产品名称',
      '产品编码',
      '产品规格',
      '品牌',
      '采购数量',
      '单价',
      '金额'
    ]

    // 处理数据行
    const rows = []
    allOrders.forEach(order => {
      // 计算订单总金额和产品数量
      let totalAmount = 0
      let totalQuantity = 0
      
      if (order.details && order.details.length > 0) {
        totalAmount = order.details.reduce((sum, detail) => {
          return sum + (detail.po_number || 0) * (detail.details_monovalent || 0)
        }, 0)
        
        totalQuantity = order.details.reduce((sum, detail) => {
          return sum + (detail.po_number || 0)
        }, 0)
      }

      // 添加主订单信息
      rows.push([
        order.po_Code || '',
        formatDate(order.create_Time) || '',
        order.po_Vendor_Name || '',
        `¥${totalAmount.toFixed(2)}`,
        totalQuantity,
        getStatusText(order.po_State),
        pb_codevalue(order.po_Code),
        formatDate(pb_timevalue(order.po_Code)),
        order.contacts_Name || '',
        order.contacts_Phone || '',
        order.create_By || '',
        order.remark || '',
        '', // 产品名称
        '', // 产品编码
        '', // 产品规格
        '', // 品牌
        '', // 采购数量
        '', // 单价
        ''  // 金额
      ])

      // 添加明细数据（如果有）
      if (order.details && order.details.length > 0) {
        order.details.forEach(detail => {
          rows.push([
            '', // 订单编号（留空，与主订单合并）
            '', // 订单日期
            '', // 供应商
            '', // 订单金额
            '', // 产品数量
            '', // 订单状态
            '', // 入库单号
            '', // 入库日期
            '', // 联系人
            '', // 联系电话
            '', // 创建人
            '', // 备注
            // 以下是明细数据
            detail.pro_name || '',
            detail.pro_code || '',
            detail.pro_model || '',
            detail.pro_brand || '',
            detail.po_number || 0,
            `¥${detail.details_monovalent || 0}`,
            `¥${(detail.po_number || 0) * (detail.details_monovalent || 0)}`
          ])
        })
      }
    })

    // 定义需要合并的列
    const mergeColumns = [
      '订单编号',
      '订单日期',
      '供应商',
      '订单金额',
      '产品数量',
      '订单状态',
      '入库单号',
      '入库日期',
      '联系人',
      '联系电话',
      '创建人',
      '备注'
    ]

    // 发送导出请求
    const exportResponse = await axios.post('http://localhost:5181/api/SystemHome/ExportExcel', {
      headers: headers,
      rows: rows,
      title: "采购订单信息",
      mergeColumns: mergeColumns
    }, {
      responseType: 'blob'
    })

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([exportResponse.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '采购订单信息.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出 Excel 失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

    // 跳转详情（示例未实现）
    function viewDetail(row) {
      // ElMessage.info(`查看订单 ${row.po_code} 详情`)
      // console.log(row)
      store.commit('PO_UpdeteArray', row)
      Router.push({
                path: '/main/Pinv/PoInfo',
                // query:{
                //     rowData: JSON.stringify(row)
                // }
            })
    }

    // 返回模板需要的变量和方法
    return {
      currentPage,
      pageSize,
      pageCount,
      count,
      tableData,
      caigouzonjine,
      danjia,
      vendornumer,
      monthlyTrendChart,
      vendorPieChart,
      pbdata,
      tabledatapo,
      customerTable,
      getTableHeaders,
      handleSizeChange,
      handleCurrentChange,
      formatDate,
      getStatusText,
      getStatusTagType,
      initMonthlyTrendChart,
      Counts,
      initData,
      vendorCount,
      exportExcel,
      viewDetail,
      zjevalue,
      shulvalue,
      pb_codevalue,
      pb_timevalue
    }
  }
}
</script>

<style scoped>
.purchase-statistics-container {
  padding: 20px;
  margin-top: -50px;
}

.chart-container {
  margin-bottom: 40px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
  color: #303133;
}

.chart {
  height: 300px;
  width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

.statistics-overview {
  margin-bottom: 20px;
  width: 100%;
  margin-top: -30px;
}

.stat-card {
  flex: 1;
  min-width: 0; /* 防止内容溢出导致卡片缩小 */
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 5px; /* 卡片间添加小间距 */
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.stat-item {
  text-align: center;
  padding: 0 10px; /* 内容内边距 */
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
  white-space: nowrap; /* 标签不换行 */
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis; /* 数值过长时省略 */
  white-space: nowrap;
}

.detail-table {
  margin-bottom: 20px;
  margin-top: -10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.el-pagination {
  margin-top: 15px;
  text-align: right;
}

/* 响应式优化：小屏幕下卡片堆叠 */
@media (max-width: 768px) {
  .statistics-overview .el-col {
    width: 100%; /* 小屏幕下每个卡片占满一行 */
    margin-bottom: 10px;
  }
}
</style>